﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;

namespace DiamondDesktop.Presenters
{
    class Properties
    {
        private Hashtable properties = new Hashtable();
        private static Properties instance = null;

        public static Properties getInstance()
        {
            if (instance == null)
            {
                instance = new Properties();
            }
            return instance;
        }
        private Properties()
        {
            load();
            if (properties[Config.LAST_USE_TIME] == null)
            {
                setDefaultValues();
                store();
            }
        }

        private void setDefaultValues()
        {
            Hashtable t = Config.defaults();
            IDictionaryEnumerator it = t.GetEnumerator();
            while (it.MoveNext())
            {
                properties.Add(it.Entry.Key, it.Entry.Value);
            }
        }

        public string getProperty(string key)
        {
            return (string)properties[key];
        }

        public void setProperty(string key, Object value)
        {
            properties[key] = value;
            store();
        }

        public bool load()
        {
            try
            {
                FileStream outFile = new FileStream(Config.CONFIG_FILE_NAME, FileMode.Open, FileAccess.Read);
                StreamReader writer = new StreamReader(outFile);
                string line;
                properties.Clear();
                while (writer.Peek() != -1)
                {
                    line = writer.ReadLine();
                    string[] tokens = line.Split("=".ToCharArray());
                    if (tokens.Length == 2)
                        properties.Add(tokens[0], tokens[1]);
                }
                writer.Close();
                outFile.Close();
            }
            catch (IOException e)
            {
                return false;
            }
            return true;
        }

        public bool store()
        {
            try
            {
                FileStream outFile = new FileStream(Config.CONFIG_FILE_NAME, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter writer = new StreamWriter(outFile);
                foreach (Object key in properties.Keys)
                {
                    writer.WriteLine(key + "=" + properties[key]);
                }
                writer.Close();
                outFile.Close();
            }
            catch (IOException e)
            {
                return false;
            }
            return true;
        }

    }
}
